<?php

namespace App\Services\AliOss;

use App\Services\AliOss\OSS\OssClient;
use Illuminate\Support\Facades\Log;

trait AliOssAdapterTrait
{
    public function getOssAdapter($config): AliOssAdapter
    {
        $accessId = $config['access_id'];
        $accessKey = $config['access_key'];

        $cdnDomain = empty($config['cdnDomain']) ? '' : $config['cdnDomain'];
        $bucket = $config['bucket'];
        $ssl = empty($config['ssl']) ? false : $config['ssl'];
        $isCname = empty($config['isCName']) ? false : $config['isCName'];
        $debug = empty($config['debug']) ? false : $config['debug'];
        $prefix = empty($config['prefix']) ? null : $config['prefix'];

        $endPoint = $config['endpoint']; // 默认作为外部节点
        $epInternal = $isCname ? $cdnDomain : (empty($config['endpoint_internal']) ? $endPoint : $config['endpoint_internal']); // 内部节点

        if ($debug) Log::debug('OSS config:', $config);

        $client = new OssClient($accessId, $accessKey, $epInternal, $isCname);
        $adapter = new AliOssAdapter($client, $bucket, $endPoint, $ssl, $isCname, $debug, $cdnDomain, $prefix);

        if (!empty($config['sts']['acessKeyID']) && !empty($config['sts']['accessKeySecret'])) {
            if (empty($config['sts']['bucket'])) {
                $config['sts']['bucket'] = $bucket;
            }
            if (empty($config['sts']['endpoint'])) {
                $config['sts']['endpoint'] = $endPoint;
            }
            $adapter->setStsConfig($config['sts']);
        }
        return $adapter;
    }

}
